import socket
import threading


def handle_client(client_socket, client_address):
    """处理客户端连接的函数"""
    print(f"新连接: {client_address}")

    try:
        # 循环接收客户端消息
        while True:
            # 接收客户端发送的数据，缓冲区大小为1024字节
            data = client_socket.recv(1024)
            if not data:
                # 如果没有数据，说明客户端断开连接
                print(f"客户端 {client_address} 断开连接")
                break

            # 解码收到的数据并打印
            message = data.decode('utf-8')
            print(f"来自 {client_address} 的消息: {message}")

            # 服务端输入回复消息
            response = input("请输入回复: ")
            # 发送回复给客户端
            client_socket.sendall(response.encode('utf-8'))

    except Exception as e:
        print(f"与 {client_address} 通信时发生错误: {e}")
    finally:
        # 关闭客户端套接字
        client_socket.close()


def start_server(host='0.0.0.0', port=12345):
    """启动TCP服务器"""
    # 创建TCP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 绑定到指定的主机和端口
        server_socket.bind((host, port))
        print(f"服务器绑定到 {host}:{port}")

        # 开始监听连接，最大连接数为5
        server_socket.listen(5)
        print("服务器启动，等待客户端连接...")

        while True:
            # 接受客户端连接
            client_socket, client_address = server_socket.accept()

            # 创建新线程处理客户端连接
            client_thread = threading.Thread(
                target=handle_client,
                args=(client_socket, client_address)
            )
            client_thread.start()
            print(f"当前活跃连接数: {threading.active_count() - 1}")

    except Exception as e:
        print(f"服务器发生错误: {e}")
    finally:
        # 关闭服务器套接字
        server_socket.close()
        print("服务器已关闭")


if __name__ == "__main__":
    start_server()
